
/*
 * JQuery zTree core v3.5.15
 * http://zTree.me/
 *
 * Copyright (c) 2010 Hunter.z
 *
 * Licensed same as jquery - MIT License
 * http://www.opensource.org/licenses/mit-license.php
 *
 * email: hunter.z@263.net
 * Date: 2013-10-15
 */

//2014年3月17日 tony add
//Tree与其他 DOM 拖拽互动
var newDomURL ;//新创建的对象URL
var DargTree = {
	errorMsg: "放错了...请选择正确的类别！",
	curTarget: null,
	curTmpTarget: null,
	lastObj:{
		target:null,//前一个目标
		index:null, //前一个目标的index
		position:null//位置 top
	},
	noSel: function() {
		try {
			window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
		} catch(e){}
	},
	dragTree2Dom: function(treeId, treeNodes) {
		return !treeNodes[0].isParent;
	},
	prevTree: function(treeId, treeNodes, targetNode) {
		return !targetNode.isParent && targetNode.parentTId == treeNodes[0].parentTId;
	},
	nextTree: function(treeId, treeNodes, targetNode) {
		return !targetNode.isParent && targetNode.parentTId == treeNodes[0].parentTId;
	},
	innerTree: function(treeId, treeNodes, targetNode) {
		return targetNode!=null && targetNode.isParent && targetNode.tId == treeNodes[0].parentTId;
	},
	dragMove: function(e, treeId, treeNodes) { //拖动过程中
		if(DargTree.lastObj.target){//移除div
			DargTree.lastObj.target.css({
						 "width":"0",
						 "height":"0",
						 "left":"0",
						 "top":"0"
					 });
		}
		//如果是在表格上移动
		if($(e.target).closest(".selectableTable").length > 0){
			 DargTree.lastObj.target = $(e.target).closest(".selectableTable").prev();
			 if($(e.target).closest("thead").length>0){ //如果是表头 可以添加行
				var width = $(e.target).closest(".selectableTable").width() < $(e.target).closest(".newDom").width()?$(e.target).closest(".selectableTable").width():$(e.target).closest(".newDom").width();
				if(e.pageY < $(e.target).offset().top+$(e.target).height()/2){//上
					DargTree.lastObj.position = "top";
					DargTree.lastObj.target.css({
						 "width":width+"px",
						 "height":"3px",
						 "left":"0",
						 "top":$(e.target).position().top+"px"
					});
				}else{//下
					DargTree.lastObj.target.css({
						 "width":width+"px",
						 "height":"3px",
						 "left":"0",
						 "top":$(e.target).position().top+$(e.target).height()-3+"px"
					});
					DargTree.lastObj.position = "bottom";
				}
			 }else{ //如果不是表头 可以添加列
				var height = $(e.target).closest(".selectableTable").height() < $(e.target).closest(".newDom").height() ? $(e.target).closest(".selectableTable").height() : $(e.target).closest(".newDom").height();
                if (e.pageX < $(e.target).offset().left + $(e.target).width() / 2) { //左
                    DargTree.lastObj.target.css({
                        "width": "3px",
                        "height": height + "px",
                        "top": "0px",
                        "left": $(e.target).position().left + "px"
                    });
                    DargTree.lastObj.position = "left";
                } else { //右
                    DargTree.lastObj.target.css({
                        "width": "3px",
                        "height": height + "px",
                        "top": "0px",
                        "left": $(e.target).position().left + $(e.target).width()+ 10+"px"

                    });
                    DargTree.lastObj.position = "right";
                }
			 }
		}
	},
	dropTree2Dom: function(e, treeId, treeNodes, targetNode, moveType) {
		if(DargTree.lastObj.target){
			DargTree.lastObj.target.css({
						 "width":"0",
						 "height":"0",
						 "left":"0",
						 "top":"0"
					 });
		}
		var nodeid = treeNodes[0].id;
		var pId = null ;
		if(treeNodes[0].getParentNode() !=null ){
			pId = treeNodes[0].getParentNode().id;
		}
		if (moveType == null) {//拖入松开鼠标时，向designer_k添加div
			var activeIndex = $(".left_btm a.active").attr("data-id");
			var ids ="";
			for(i=0 ; i<treeNodes.length ; i++){
			   ids = ids+treeNodes[i].lid+"," ;
			}
			
			if(treeNodes[0].tasktype !=null){
				location.href = url_list.addtask_url+'?tasktype='+treeNodes[0].tasktype ;		
			}else if($(e.target).parents(".event_design").length > 0 || $(e.target).parents("body").length == 0){
				if($(e.target).hasClass("tasknodeattribute")){
					BtnAction.operators($(e.target) , treeNodes[0].value);
				}else if($(e.target).parents("body").length == 0 && um!=null){
					um.execCommand("inserthtml",treeNodes[0].value);
				}
			}else if($(e.target).hasClass("designer_k") && $(".left_btm a.active").length ==0){
				loadURL(ReportURL.designReportURL+"?type="+treeNodes[0].type+"&oid="+ids+"&pos="+DargTree.lastObj.position+"&index="+thIndex,'#design_table');
			}else if($(e.target).hasClass("designer_k")){		   //如果是直接拖拽到designer_k内而且拖的是组件树里面的元素 
				if(activeIndex != 1){
					//设置新div放置的位置
					var style = "";
					var top = e.pageY-$(e.target).offset().top+"px";
					var left = e.pageX-$(e.target).offset().left+"px";
					style = ' style="position:absolute;top:'+top+';left:'+left+'"';
					if($(e.target).hasClass("layout")){
						style = ' style="width:250px;float:left;}"';
						$(e.target).append("<div class=\"newDom span2 newnewDom\""+style+"><div class=\"table_menu\"><div class=\"table_menu_inner\"><span class=\"tool-icons-1\"></span><span class=\"tool-icons-1\"></span><em class='tool-ctr-close'></em></div></div>"+treeNodes[0].name+"</div>");
                        var span_arr = [0,0.078,0.162,0.246,0.330,0.414,0.497,0.581,0.665,0.749,0.833,0.917,1];
                        $(e.target).find(".newnewDom").resizable({//添加可改变尺寸效果
                            handles: "e, s, w, se, sw",
                            stop:function (event, ui) {
								//如果resize 后left小于0
								if($(event.target).position().left<0){
									$(event.target).css('left',0);
								}
								//如果resize 后宽度大于父级宽度
								if (ui.size.width/$(e.target).width() >= 1) {
									$(event.target).attr('class',"").addClass('span12').addClass('newDom ui-resizable').css('width',"");
									return;
								} 
                                for (var i = 1; i < span_arr.length; i++) {
                                     // if we found the desired number, we return it.
                                     if (ui.size.width/$(e.target).width() < span_arr[i]) {
//                                          $(event.target).css('width',span_div.attr('class',"").addClass('span'+i).width()+'px');
                                          $(event.target).attr('class',"").addClass('span'+i).addClass('newDom ui-resizable').css('width',"");
                                          return;
                                     } 
                               }    
                            }
                        })
                        .removeClass("newnewDom"); //移除clas--newnewDom
					}else{
						style = ' style="position:absolute;top:'+top+';left:'+left+'"';
						$(e.target).append("<div class=\"newDom newnewDom\""+style+"><div class=\"table_menu\"><div class=\"table_menu_inner\"></span><span class=\"tool-icons-1\"></span><span class=\"tool-icons-1\"></span><em class='tool-ctr-close'></em></div></div>"+treeNodes[0].name+"</div>");
                        $(e.target).find(".newnewDom").resizable({//添加可改变尺寸效果
                            handles: "e, s, w, se, sw",
                            containment:"parent"
                            //handles: "e, s, w"
                        })
                        .draggable({containment:"parent"}) //添加拖动效果
                        .removeClass("newnewDom"); //移除clas--newnewDom
					}
				}else{
					if($(e.target).hasClass("layout")){
						//
					}else{
						$(e.target).append("<div class=\"row-fluid designer_k layout newnewDom clearfix\" style='min-height:50px;border:2px dotted #c6c6c6;position:relative;'></div>");
                        $(e.target).find(".newnewDom").sortable({//添加可改变尺寸效果
                            placeholder: "ui-state-highlight",
							helper: "clone",
							item:".newDom",
                            start:function (event, ui) {
								$(event.target).find(".ui-state-highlight").css({
									"height": ui.item.outerHeight(),
									"float":"left"
								});
								ui.helper.css({
									"height": ui.item.height()
								})
                            }
                        })
                        .removeClass("newnewDom"); //移除clas--newnewDom
					}
				}
			//如果是拖拽到表格中
			}else if($(e.target).closest(".selectableTable").length > 0){
				var targetIndex = $(e.target).index();
				if(DargTree.lastObj.position == "right" && $(e.target).attr("colspan")>1){
					targetIndex += $(e.target).attr("colspan")-1;
				}
				var thIndex = $(e.target).closest(".selectableTable")
							.find("thead tr.sortableTr").find('td')
							.eq(targetIndex).attr("data-id");
				loadURL(ReportURL.designReportURL+"?type="+treeNodes[0].type+"&oid="+ids+"&pos="+DargTree.lastObj.position+"&index="+thIndex,'#design_table');
				//alert("nodeId:"+nodeid+",table:"+$(e.target).parents(".selectableTable").attr('data-id')+",pId:"+pId+",index:"+thIndex+",position:"+DargTree.lastObj.position);
			//如果是拖拽到newDom div内
			}else if($(e.target).hasClass("newDom") && activeIndex != 1){
				//$(e.target).append("<div>"+treeNodes[0].name+"</div>");
			//如果是拖拽到顶部的div内
			}else if($(e.target).closest(".nr").length > 0){
				if(treeNodes[0].type == "dimensions"){//只处理维度
					tipArtPage("添加过滤器" , url_list.filterparam_url+"?name=" + encodeURIComponent(treeNodes[0].name) + "&dimid="+treeNodes[0].dimid+"&levelid="+treeNodes[0].lid,750);
				}
            }
			//更新节点，此处不需要
			//var zTree = $.fn.zTree.getZTreeObj("zTree_adminLIst");
			//zTree.removeNode(treeNodes[0]);
			//DargTree.updateType();
		}
		
	},
	dom2Tree: function(e, treeId, treeNode) {
		var target = DargTree.curTarget, tmpTarget = DargTree.curTmpTarget;
		if (!target) return;
		var zTree = $.fn.zTree.getZTreeObj("zTree_adminLIst"), parentNode;
		if (treeNode != null && treeNode.isParent && "dom_" + treeNode.id == target.parent().attr("id")) {
			parentNode = treeNode;
		} else if (treeNode != null && !treeNode.isParent && "dom_" + treeNode.getParentNode().id == target.parent().attr("id")) {
			parentNode = treeNode.getParentNode();
		}

		if (tmpTarget) tmpTarget.remove();
		if (!!parentNode) {
			var nodes = zTree.addNodes(parentNode, {id:target.attr("domId"), name: target.text()});
			zTree.selectNode(nodes[0]);
		} else {
			target.removeClass("domBtn_Disabled");
			target.addClass("domBtn");
			alert(DargTree.errorMsg);
		}
		DargTree.updateType();
		DargTree.curTarget = null;
		DargTree.curTmpTarget = null;
	},
	updateType: function() {
		var zTree = $.fn.zTree.getZTreeObj("zTree_adminLIst"),
		nodes = zTree.getNodes();
		for (var i=0, l=nodes.length; i<l; i++) {
			var num = nodes[i].children ? nodes[i].children.length : 0;
			nodes[i].name = nodes[i].name.replace(/ \(.*\)/gi, "") + " (" + num + ")";
			zTree.updateNode(nodes[i]);
		}
	},
	bindDom: function() {
		$(".designer_k").bind("mousedown", DargTree.bindMouseDown);
	},
	bindMouseDown: function(e) {
		var target = e.target;
		if (target!=null && target.className=="domBtn") {
			var doc = $(document), target = $(target),
			docScrollTop = doc.scrollTop(),
			docScrollLeft = doc.scrollLeft();
			target.addClass("domBtn_Disabled");
			target.removeClass("domBtn");
			curDom = $("<span class='dom_tmp domBtn'>" + target.text() + "</span>");
			curDom.appendTo("body");

			curDom.css({
				"top": (e.clientY + docScrollTop + 3) + "px",
				"left": (e.clientX + docScrollLeft + 3) + "px"
			});
			DargTree.curTarget = target;
			DargTree.curTmpTarget = curDom;

			doc.bind("mousemove", DargTree.bindMouseMove);
			doc.bind("mouseup", DargTree.bindMouseUp);
			doc.bind("selectstart", DargTree.docSelect);
		}
		if(e.preventDefault) {
			e.preventDefault();
		}
	},
	bindMouseMove: function(e) {
		DargTree.noSel();
		var doc = $(document), 
		docScrollTop = doc.scrollTop(),
		docScrollLeft = doc.scrollLeft(),
		tmpTarget = DargTree.curTmpTarget;
		if (tmpTarget) {
			tmpTarget.css({
				"top": (e.clientY + docScrollTop + 3) + "px",
				"left": (e.clientX + docScrollLeft + 3) + "px"
			});
		}
		return false;
	},
	bindMouseUp: function(e) {
		var doc = $(document);
		doc.unbind("mousemove", DargTree.bindMouseMove);
		doc.unbind("mouseup", DargTree.bindMouseUp);
		doc.unbind("selectstart", DargTree.docSelect);

		var target = DargTree.curTarget, tmpTarget = DargTree.curTmpTarget;
		if (tmpTarget) tmpTarget.remove();

		if ($(e.target).parents("#zTree_adminLIst").length == 0) {
			if (target) {
				target.removeClass("domBtn_Disabled");
				target.addClass("domBtn");
			}
			DargTree.curTarget = null;
			DargTree.curTmpTarget = null;
		}
	},
	bindSelect: function() {
		return false;
	}
};

//setting_1
var treeNiceScroll = false;
var setting = {
    edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false,
				drag: {
					prev: DargTree.prevTree,
					next: DargTree.nextTree,
					inner: DargTree.innerTree
				}
			},
	data: {
        keep: {
					parent: true,
					leaf: true
				},
		simpleData: {
			enable: true
		}
	},
	callback: {
        onDrop: DargTree.dropTree2Dom,
        onDragMove: DargTree.dragMove,
        onMouseUp: DargTree.dom2Tree,
		//onCollapse: alert("up"),
		onExpand: function(){
			if (treeNiceScroll) {
				treeNiceScroll.resize();
			}
		}
	},
	view: {
		showLine: false,
		nameIsHTML: true
	}
};
